package com.yanftch.stopcoding.ui.rotate;

import com.yanftch.stopcoding.bean.HotBean;

import java.net.URI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * OK了，但是是居中对齐的
 */
public class RotatedLabel_ok extends JLabel {
    private int angle; // 旋转角度

    public RotatedLabel_ok(HotBean hotBean, int angle) {
        super(hotBean.getTitle());
        this.angle = angle;
        setFont(new Font("Arial", Font.PLAIN, 16)); // 设置字体
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                try {
                    Desktop.getDesktop().browse(new URI(hotBean.getUrl()));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create(); // 创建Graphics2D副本
        String text = getText();

        // 获取字体度量信息
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(text);
        int textHeight = fm.getHeight();

        // 设置颜色
        g2d.setColor(getForeground());

        // 根据旋转角度调整绘制位置
        if (angle == -90) {
            // 左旋转90度
            g2d.rotate(Math.toRadians(angle), 0, 0);
            g2d.translate(-getHeight(), 0); // 左旋转后调整位置
        } else if (angle == 90) {
            // 右旋转90度
            g2d.rotate(Math.toRadians(angle), 0, 0);
            g2d.translate(0, -getWidth()); // 右旋转后调整位置
        }

        // 绘制文本，底部对齐
        g2d.drawString(text, 0, fm.getAscent());

        g2d.dispose(); // 释放Graphics资源
    }

    @Override
    public Dimension getPreferredSize() {
        // 交换宽度和高度以适应旋转后的文本
        FontMetrics fm = getFontMetrics(getFont());
        int textWidth = fm.stringWidth(getText());
        int textHeight = fm.getHeight();
        return angle == 90 || angle == -90 ? new Dimension(textHeight, textWidth) : new Dimension(textWidth, textHeight);
    }
}
